import { Controller } from 'egg';
import * as moment from 'moment';
export default class BusinessCateClass extends Controller {
    public async index() {
        const { ctx } = this;
        ctx.body = '666';
    }
    public async create() {
        const { ctx } = this;
        const { weight, name } = ctx.request.body;
        try {
            await (new ctx.model.BusinessCate({
                name,
                weight,
                createDate: moment().toDate(),
            })).save();
            const allBusinessCate =
                await ctx.model.BusinessCate.find({}, { name: 1, weight: 1 }).sort({ weight: 'desc' });
            ctx.body = allBusinessCate;
        } catch (e) {
            ctx.body = { status: -1, message: '创建失败请检查是否命名重复' };
        }
    }
    public async update() {
        const { ctx } = this;
        const { id } = ctx.params;
        try {
            await ctx.model.BusinessCate.updateOne({_id: id}, ctx.request.body);
            const allBusinessCate =
                await ctx.model.BusinessCate.find({}, { name: 1, weight: 1 }).sort({ weight: 'desc' });
            ctx.body = allBusinessCate;
        }catch(e){
            ctx.body = { status: -1, message: '更新失败请检查是否命名重复' };
        }
    }
    public async getList() {
        const { ctx } = this;
        const allBusinessCate = await ctx.model.BusinessCate.find({}, { name: 1, weight: 1 }).sort({ weight: 'desc' });
        ctx.body = allBusinessCate;
    }
    public async delete() {
        const { ctx } = this;
        const { id } = ctx.params;
        try {
            await ctx.model.BusinessCate.deleteOne({ _id: id });
            const allBusinessCate =
                await ctx.model.BusinessCate.find({}, { name: 1, weight: 1 }).sort({ weight: 'desc' });
            ctx.body = allBusinessCate;
        } catch (e) {
            ctx.body = { status: -1, message: '删除失败' };
        }
    }
}
